package com.societyGames.interceptExercises
{
import com.societyGames.action.ActionQueue;

public class InterceptSimulation
{
  private var _render:InterceptRender;
  private var _expression:INumberExpression;
  private const _getBoatXFunctionName:String = "getBoatX";
  private var _boatX:Number;
  private var _hookDepth:Number;

  public const gridWidth:int = 5;
  public const gridHeight:int = 5;

  public function InterceptSimulation(actionQueue:ActionQueue)
  {
    this._render = new InterceptRender(this, actionQueue);
  }

  public function get boatX():Number
  {
    return _boatX;
  }

  public function get render():InterceptRender
  {
    return this._render;
  }

  public function initialize(xml:XML):void
  {
    //values
    for each (var xmlChild:XML in xml.values[0].children())
    {
      FunctionCallExpression.setFunctionReturnValue(xmlChild.name(), Number(xmlChild.toString()));
    }

    //Store where the boat is supposed to be.
    _boatX = FunctionCallExpression.getFunctionReturnValue(_getBoatXFunctionName);

    //Expression
    this._expression = Parser.parse(xml.expression.children()[0]);
    this._render.setExpression(this._expression);
    if (xml.text.length() == 0)
    {
      this._render.setExpressionText(Object(this._expression).toString());
    }
    else
    {
      this._render.setExpressionText(xml.text[0].toString());
    }
  }

  public function setHookDepth(depth:Number):void
  {
    _hookDepth = depth;
    this._render.setHookDepth(_hookDepth);
  }

  public function isCaught():Boolean
  {
    return _hookDepth == calculateFishSimulationY(_boatX);
  }

  public function calculateFishSimulationY(simulationX:Number):Number
  {
    var originalBoatX:Number = FunctionCallExpression.getFunctionReturnValue(_getBoatXFunctionName);
    FunctionCallExpression.setFunctionReturnValue(_getBoatXFunctionName, simulationX);
    var fishSimulationX:Number = _expression.evaluate();
    FunctionCallExpression.setFunctionReturnValue(_getBoatXFunctionName, originalBoatX);
    return fishSimulationX;
  }
}
}

/*
 setHookDepth(getBoatX() * 4 + 10);
 setHookDepth(getBoatX() * getM() + getB());
 render the hook depth changing
 when code is all done, render the fish moving
 if (hookDepth == expression.evaluate())
 correct
 else
 fail
 */
